import frappe
from frappe.website.report.website_analytics.website_analytics import WebsiteAnalytics

def _get_query_for_dm(self):
    filters_range = self.filters.range
    field = "creation"
    granularity = "day"

    if filters_range == "Weekly":
        granularity = "week"
    elif filters_range == "Monthly":
        granularity = "month"

    query = f"""
        SELECT
            TRUNC({field}, %s) as date,
            COUNT(*) as count,
            COUNT(CASE WHEN CAST(is_unique as Integer) = 1 THEN 1 END) as unique_count
        FROM "tabWeb Page View"
        WHERE coalesce("tabWeb Page View".{field}, '0001-01-01') BETWEEN %s AND %s
        GROUP BY TRUNC({field}, %s)
        ORDER BY date
    """

    values = (granularity, self.filters.from_date, self.filters.to_date, granularity)

    return query, values

def get_chart_data(self):
    current_dialect = frappe.db.db_type or "mariadb"

    if current_dialect == "mariadb":
        query, values = self._get_query_for_mariadb()
    elif current_dialect == "postgres":
        query, values = self._get_query_for_postgres()
    else:
        query, values = self._get_query_for_dm()

    self.chart_data = frappe.db.sql(query, values=values, as_dict=1)

    return self.prepare_chart_data(self.chart_data)

def override_website_analytics():
    WebsiteAnalytics._get_query_for_dm = _get_query_for_dm
    WebsiteAnalytics.get_chart_data = get_chart_data
